package edu.sctu.yueding.activitys;

import android.app.Activity;
import android.app.ProgressDialog;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.android.volley.Response;
import com.android.volley.VolleyError;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import edu.sctu.yueding.R;
import edu.sctu.yueding.adapter.MyFriendMemberListAdapter;
import edu.sctu.yueding.bean.JsonBaseListBean;
import edu.sctu.yueding.bean.FriendBean;
import edu.sctu.yueding.bean.UserBean;
import edu.sctu.yueding.config.CacheConfig;
import edu.sctu.yueding.config.URLConfig;
import edu.sctu.yueding.utils.CharacterParser;
import edu.sctu.yueding.utils.DateUtils;
import edu.sctu.yueding.utils.JumpUtils;
import edu.sctu.yueding.utils.PinyinComparator;
import edu.sctu.yueding.utils.ProgressUtil;
import edu.sctu.yueding.utils.SideBar;
import edu.sctu.yueding.utils.httputils.GetVolleyHttp;
import edu.sctu.yueding.utils.httputils.SharePreference;
import edu.sctu.yueding.view.XListView;
import io.rong.imkit.RongIM;
import io.rong.imlib.model.Conversation;
import io.rong.imlib.model.UserInfo;

/**
 * Created by 鑫爷您慢点 on 2016/8/2.
 */
public class MyFriendsActivity extends BaseActivity implements XListView.IXListViewListener, View.OnClickListener, AdapterView.OnItemClickListener, RongIM.UserInfoProvider, SideBar.OnTouchingLetterChangedListener, TextWatcher {

    private XListView listView;
    private TextView mBackTxt;
    private Activity mActivity = this;

    private SharePreference sharePreference;
    private String token;
    private List<UserBean> datas;

    private Handler handler = new Handler();
    private ProgressUtil progressUtil;
    private String show = null;
    private ProgressDialog progressDialog;

    private boolean isAddAll = true;
    private TextView tvConversion;
    private ImageView newPoint;


    private SideBar mSideBar;

    private TextView mDialog;

    private EditText mSearchInput;

    private CharacterParser characterParser;// 汉字转拼音

    private PinyinComparator pinyinComparator;// 根据拼音来排列ListView里面的数据类

    private List<FriendBean> sortDataList;
    private List<FriendBean> friendList;


    private MyFriendMemberListAdapter mAdapter;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_my_friends);

        initView();
        initSystemBar(this, 0);
    }

    private void initView() {

        listView = (XListView) findViewById(R.id.school_friend_member);
        listView.setPullLoadEnable(false);
        listView.setPullRefreshEnable(false);
        listView.setXListViewListener(this);

        listView.setOnItemClickListener(this);

        tvConversion = (TextView) findViewById(R.id.id_conversion);
        newPoint = (ImageView) findViewById(R.id.im_new_point);
        mBackTxt = (TextView) findViewById(R.id.id_my_friends_back_txt);
        sharePreference = SharePreference.getInstance(this);
        token = sharePreference.getString("token");
        progressUtil = ProgressUtil.getInstance(this, show);
        newPoint.setVisibility(View.GONE);


        mSideBar = (SideBar) findViewById(R.id.school_friend_sidrbar);
        mDialog = (TextView) findViewById(R.id.school_friend_dialog);
        mSearchInput = (EditText) findViewById(R.id.school_friend_member_search_input);

        mSideBar.setTextView(mDialog);
        mSideBar.setOnTouchingLetterChangedListener(this);


        progressDialog = progressUtil.getProgressDialog(ProgressDialog.STYLE_SPINNER, true);

        handler.postDelayed(new Runnable() {
            @Override
            public void run() {

                initData();
            }

        }, 1000);


        setEvent();

        isRead();

    }

    private void initData() {

        // 实例化汉字转拼音类
        characterParser = CharacterParser.getInstance();
        pinyinComparator = new PinyinComparator();
        GetVolleyHttp.getInstance(this).getStringGETJsonData(URLConfig.MY_FRIENDS, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {

                JsonBaseListBean<UserBean> u = JSON.parseObject(response, new TypeReference<JsonBaseListBean<UserBean>>() {
                }.getType());

                if (u.getMeta().code == 200) {
                    datas = u.getData();
                    if (datas == null) {

                        Toast.makeText(mActivity, "暂无好友", Toast.LENGTH_SHORT).show();

                    } else {

                        sortDataList = new ArrayList<>();
                        friendList = new ArrayList<>();

                        for (UserBean user : datas) {

                            sortDataList.add(new FriendBean(String.valueOf(user.getId()),user.getNickname(),user.getAvatarUrl()));
                            friendList.add(new FriendBean(String.valueOf(user.getId()),user.getNickname(),user.getAvatarUrl()));
                        }

                        RongIM.setUserInfoProvider(MyFriendsActivity.this, true);
                        initAdapter(sortDataList);
                    }
                }
                progressUtil.dismiss(progressDialog);

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.d("myFriend", "myFriend error");
            }
        }, "Bearer " + token);
    }


    private void initAdapter(List<FriendBean> datas) {

        if (mAdapter == null) {
            fillData(datas);
            // 根据a-z进行排序源数据
            Collections.sort(datas, pinyinComparator);

            mAdapter = new MyFriendMemberListAdapter(this, datas);
            listView.setAdapter(mAdapter);

        } else {
            mAdapter.fresh(datas, isAddAll);
        }

        stop();
    }

    private void stop() {
        listView.stopLoadMore();
        listView.stopRefresh();
        listView.setRefreshTime(DateUtils.getTime());
    }

    private void setEvent() {

        RongIM.setUserInfoProvider(this, true);
        tvConversion.setOnClickListener(this);
        mBackTxt.setOnClickListener(this);
        mSearchInput.addTextChangedListener(this);

    }

    /**
     * 填充数据
     *
     * @param list
     */
    private void fillData(List<FriendBean> list) {
        for (FriendBean cUserInfoDto : list) {
            if (cUserInfoDto != null && cUserInfoDto.getName() != null) {
                String pinyin = characterParser.getSelling(cUserInfoDto.getName());
                String suoxie = CharacterParser.getFirstSpell(cUserInfoDto.getName());

                cUserInfoDto.setSuoxie(suoxie);
                String sortString = pinyin.substring(0, 1).toUpperCase();

                if ("1".equals(cUserInfoDto.getUtype())) {// 判断是否是管理员
                    cUserInfoDto.setSortLetters("☆");
                } else if (sortString.matches("[A-Z]")) {// 正则表达式，判断首字母是否是英文字母
                    cUserInfoDto.setSortLetters(sortString);
                } else {
                    cUserInfoDto.setSortLetters("#");
                }
            }
        }
    }

    /**
     * 根据输入框中的值来过滤数据并更新ListView
     *
     * @param filterStr
     */
    private void filterData(String filterStr, List<FriendBean> list) {

        List<FriendBean> filterDateList = new ArrayList<FriendBean>();


        Log.e("rrrr", "5555555");

        if (TextUtils.isEmpty(filterStr)) {
            filterDateList = list;
        } else {
            filterDateList.clear();
            for (FriendBean sortModel : list) {
                String name = sortModel.getName();
                String suoxie = sortModel.getSuoxie();
                if (name.indexOf(filterStr.toString()) != -1 || suoxie.indexOf(filterStr.toString()) != -1 || characterParser.getSelling(name).startsWith(filterStr.toString())) {
                    filterDateList.add(sortModel);
                }
            }
        }

        // 根据a-z进行排序
        Collections.sort(filterDateList, pinyinComparator);
        mAdapter.updateListView(filterDateList);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.id_my_friends_back_txt:

                Bundle bundle = new Bundle();
                bundle.putInt("flag", 3);
                JumpUtils.activityToFragmentJump(MyFriendsActivity.this, bundle);

                break;
            case R.id.id_conversion:

                if (RongIM.getInstance() != null)
                    RongIM.getInstance().startConversationList(MyFriendsActivity.this);

                break;
            default:
                break;
        }
    }

    @Override
    public void onRefresh() {
        isAddAll = false;
        initData();
    }

    @Override
    public void onLoadMore() {
        isAddAll = true;
        initData();
    }

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

        FriendBean p = (FriendBean) mAdapter.getItem(i - 1);


        //启动会话界面
        if (RongIM.getInstance() != null)
            RongIM.getInstance().startPrivateChat(MyFriendsActivity.this, String.valueOf(p.getUserId()), "title");

    }

    @Override
    public UserInfo getUserInfo(String s) {

        for (FriendBean i : friendList) {
            if (i.getUserId().equals(s)) {
                Log.e("5554343erfe", i.getHead());
                return new UserInfo(String.valueOf(i.getUserId()), i.getName(), Uri.parse(i.getHead()));
            }
        }

        return null;
    }

    @Override
    public void onTouchingLetterChanged(String s) {

        int position = 0;
        // 该字母首次出现的位置
        if (mAdapter != null) {
            position = mAdapter.getPositionForSection(s.charAt(0));
        }
        if (position != -1) {
            listView.setSelection(position);
        }
    }

    @Override
    public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

    }

    @Override
    public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
// 当输入框里面的值为空，更新为原来的列表，否则为过滤数据列表

        if (sortDataList != null){
            filterData(charSequence.toString(), sortDataList);
        }
    }

    @Override
    public void afterTextChanged(Editable editable) {

    }


    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK
                && event.getRepeatCount() == 0) {

            Bundle bundle = new Bundle();
            bundle.putInt("flag", 3);
            JumpUtils.activityToFragmentJump(MyFriendsActivity.this, bundle);

            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    public void isRead() {
        if (RongIM.getInstance() != null && sharePreference.getString(CacheConfig.CHAT_TOKEN) != null) {
            /**
             * 接收未读消息的监听器。
             *
             * @param listener          接收所有未读消息消息的监听器。
             */
//            RongIM.getInstance().setOnReceiveUnreadCountChangedListener(new MyReceiveUnreadCountChangedListener());

            /**
             * 设置接收未读消息的监听器。
             *
             * @param listener          接收未读消息消息的监听器。
             * @param conversationTypes 接收指定会话类型的未读消息数。
             */
            RongIM.getInstance().setOnReceiveUnreadCountChangedListener(new MyReceiveUnreadCountChangedListener(), Conversation.ConversationType.PRIVATE);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        isRead();
    }

    /**
     * 接收未读消息的监听器。
     */
    private class MyReceiveUnreadCountChangedListener implements RongIM.OnReceiveUnreadCountChangedListener {

        /**
         * @param count 未读消息数。
         */
        @Override
        public void onMessageIncreased(int count) {

            if (count > 0) {
                newPoint.setVisibility(View.VISIBLE);
            }
        }
    }
}
